package com.leyou.sms.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.leyou.common.utils.JsonUtils;
import com.leyou.sms.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.leyou.sms.constants.SmsConstants.*;


@Slf4j
@Component
public class SmsUtil {

    @Autowired
    private SmsProperties prop;
    @Autowired
    private IAcsClient client;

    /**
     * @param phone
     * @param code
     */
    public void sendVerifyCodeMessage(String phone, String code) {
        try {
            sendMessage(phone, prop.getSignName(), prop.getVerifyCodeTemplate(),
                    String.format(VERIFY_CODE_PARAM_TEMPLATE, code));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param phoneNumber
     * @param signName
     * @param template
     * @param param
     */
    public void sendMessage(String phoneNumber, String signName, String template, String param) {
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(prop.getDomain());
        request.setSysVersion(prop.getVersion());
        request.setSysAction(prop.getAction());
        request.putQueryParameter("RegionId", prop.getRegionID());
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", template);
        request.putQueryParameter("TemplateParam", param);
        try {
            // 2.发送请求
            CommonResponse response = client.getCommonResponse(request);

            // 3.解析结果
            Map<String, String> data = JsonUtils.toMap(response.getData(), String.class, String.class);
            // 3.1.判断业务标示
            if (!OK.equals(data.get(SMS_RESPONSE_KEY_CODE))) {
                // 失败
                log.error("发送短信失败，原因：{}", data.get(SMS_RESPONSE_KEY_MESSAGE));
                throw new RuntimeException(data.get(SMS_RESPONSE_KEY_MESSAGE));
            }
            log.debug("发送短信成功，手机号:{}", phoneNumber);
        } catch (ServerException e) {
            log.error("发送短信失败，服务端异常", e);
        } catch (ClientException e) {
            log.error("发送短信失败，客户端异常", e);
        }
    }
}



